package com.hbnu.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 需求：银行转账案例
 *
 * @author kittychen
 * @since 2025-10-21 10:40
 */
public class JdbcDemo06 {

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/class2309?serverTimezone=GMT&useSSL=false";
            String username = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, username, password);

            String sql1 = "update tb_user set salary = salary - ? where id = ?";
            String sql2 = "update tb_user set salary = salary + ? where id = ?";

            // 开启事务
            connection.setAutoCommit(false);

            // id为1的转1000
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.setDouble(1, 1000);
            preparedStatement.setInt(2, 1);
            int counts = preparedStatement.executeUpdate();

            int i = 1 / 0;

            // id为4的收款1000
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.setDouble(1, 1000);
            preparedStatement.setInt(2, 4);
            counts += preparedStatement.executeUpdate();

            // 提交事务
            connection.commit();

            System.out.println(counts == 2 ? "转账成功" : "转账失败");
        } catch (Exception e) {
            try {
                if (connection != null) {
                    // 事务回滚
                    connection.rollback();
                }
            } catch (SQLException ex) {
                e.printStackTrace();
            }
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
